package com.muyu.consumer;

import com.muyu.constant.Constants;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.support.Acknowledgment;
import org.springframework.kafka.support.KafkaHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import java.util.Optional;

/**
 * @ClassName: KafkaConsumer
 * @Author: Zirun.Xin
 * @Date: 2025/4/27 上午10:21
 * @Version: 1.0
 * @Description: kafka消费者
 */
@Slf4j
@Component
public class KafkaConsumer {

    /**
     * 消费者测试1
     * @param record 消息记录
     * @param ack 响应信号
     * @param topic 主题
     */
    @KafkaListener(topics = Constants.TEST_TOPIC, groupId = "topic.group")
    public void topicTest1(ConsumerRecord<?, ?> record, Acknowledgment ack,
                           @Header(KafkaHeaders.RECEIVED_TOPIC) String topic) {
        Optional<?> message = Optional.ofNullable(record.value());

        if(message.isPresent()) {
            Object msg = message.get();
            log.info("消费者A消费了：Topic【{}】 Message【{}】", topic, msg);
            ack.acknowledge();
        }
    }

    /**
     * 消费者测试2
     * @param record 消息记录
     * @param ack 响应信号
     * @param topic 主题
     */
    @KafkaListener(topics = Constants.TEST_TOPIC, groupId = "topic.group")
    public void topicTest2(ConsumerRecord<?, ?> record, Acknowledgment ack,
                           @Header(KafkaHeaders.RECEIVED_TOPIC) String topic) {
        Optional<?> message = Optional.ofNullable(record.value());

        if(message.isPresent()) {
            Object msg = message.get();
            log.info("消费者B消费了：Topic【{}】 Message【{}】", topic, msg);
            ack.acknowledge();
        }
    }
}
